/**
 * tags_affix为true是不可以删除
 */

// import { useRouter } from 'vue-router'
import router from '@/router'
import { handleRoutesSort } from '../../utils/route'

export default {
  namespaced: true,
  state: {
    tagsList: [],
    activeIndex: 0
  },
  mutations: {
    CHANGE_TAGS(state, tags) {
      state.tagsList = tags
    },
    CHANGE_ACTIVE_INDEX(state, index) {
      state.activeIndex = index
    }
  },
  actions: {
    /**
     * 添加固定的路由，当登录成功后添加
     * @param {*} accessRoutes 授权路由
     */
    addAffixTags({ commit }) {
      const routes = router.getRoutes()
      const tags = routes.filter((item) => item.meta && item.meta.tags_affix)
      handleRoutesSort(tags, false) // 排序处理
      commit('CHANGE_TAGS', tags)
    },
    /**
     * 添加标签，当路由切换时，通过路由Path变更判断该标签是否需要添加
     * @param {*} param
     * @param {*} route  useRoute()返回值
     * @returns
     */
    addTag({ commit, state }, route) {
      // 如果存在，就不添加
      if (state.tagsList.some((item) => item.path === route.path)) return
      const list = [...state.tagsList, route]
      commit('CHANGE_TAGS', list)
    },
    /**
     * 删除当前标签
     * @param {*} index
     */
    delTag({ commit, state }, index) {
      const list = [...state.tagsList]
      list.splice(index, 1)
      commit('CHANGE_TAGS', list)
    },

    /**
     * 删除左边标签
     * @param {*} _index 当点击右键的时候，_index才存在
     */

    delLeftTag: (...arg) =>
      handleAction(...arg, function (list, index, affix_list) {
        if (affix_list.length - 1 >= index) return affix_list

        // 固定标签 + 剩下的右边标签
        return [...affix_list, ...list.slice(index, list.length)]
      }),
    // 删除右边标签
    delRightTag: (...arg) =>
      handleAction(...arg, function (list, index, affix_list) {
        // 当指定标签在固定标签的里中
        if (affix_list.length - 1 >= index) return affix_list

        // 固定标签 + 剩下的右边标签
        return list.slice(0, index + 1)
      }),
    // 删除其他
    delOtherTag: (...arg) =>
      handleAction(...arg, function (list, index, affix_list) {
        if (affix_list.length - 1 >= index) return affix_list

        return [...affix_list, list[index]]
      }),
    // 删除全部
    delAllTag({ commit, state }) {
      const result = state.tagsList.filter((item) => item.meta.tags_affix)
      commit('CHANGE_TAGS', result)
    },
    // 修改索引，该索引是当前路由显示的索引
    changeActiveIndex({ commit }, index) {
      commit('CHANGE_ACTIVE_INDEX', index ?? 0)
    }
  }
}

function handleAction({ commit, state }, _index, cb) {
  const list = [...state.tagsList]
  const index = _index ?? state.activeIndex
  const affix_list = list.filter((item) => item.meta.tags_affix) // 固定标签不可删除
  let result = cb(list, index, affix_list)
  commit('CHANGE_TAGS', result)
}
